package com.dcivision.dms;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;

public class FolderStructureLoader {

  public static final String REVISION = "$Revision: 1.6.32.2 $";


  private List nameList = new ArrayList();
  private DocumentRetrievalManager docRetrievalManager = null;
  private DocumentOperationManager docOperationManager = null;
  private Integer startDocID = null;
  private Integer rootID = null;
  private static final Log log = LogFactory.getLog(FolderStructureLoader.class);
  public FolderStructureLoader(String fileName, Integer rootID, Integer parentID, SessionContainer sessionContainer) throws Exception {
    Connection conn = null;
    FileInputStream fis = null;

    try {
      conn = DataSourceFactory.getConnection();
      this.docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      this.docOperationManager = new DocumentOperationManager(sessionContainer, conn);
      this.startDocID = parentID;
      this.rootID = rootID;

      File excelFile = new File(fileName);

      fis = new FileInputStream(excelFile);
      Workbook workbook = Workbook.getWorkbook(fis);
      int numOfSheets = workbook.getNumberOfSheets();
      for (int i = 0; i < numOfSheets; i++) {
        String refNo = "";
        String desc = "";
        Sheet sheet = workbook.getSheet(i);
        for (int j = 1; j < sheet.getRows(); j++) {
          log.debug("Processing Sheet " + i + " Row " + j);
          Cell[] cellAry = sheet.getRow(j);

          if (cellAry.length > 0 && TextUtility.noNull(cellAry[0].getContents()).trim().length() > 0) {
            List rowList = new ArrayList();

            rowList.add(TextUtility.noNull(cellAry[0].getContents()).trim());

            if (cellAry.length > 1) {
              if (!Utility.isEmpty(cellAry[1].getContents().trim())) {
                rowList.add(TextUtility.noNull(cellAry[1].getContents()).trim());
              }

              if (cellAry.length > 2) {
                String[] splitAry = TextUtility.splitString(TextUtility.noNull(cellAry[2].getContents()).trim(), " - ");
                if (splitAry != null) {
                  for (int k = 0; k < splitAry.length; k++) {
                    rowList.add(splitAry[k]);
                  }
                }

                if (cellAry.length > 3) {
                  refNo = TextUtility.noNull(cellAry[3].getContents()).trim();

                  if (cellAry.length > 4) {
                    desc = TextUtility.noNull(cellAry[4].getContents()).trim();
                  }
                }
              }
            }

            processRow(rowList, refNo, desc);
          }
        }
      }
      conn.commit();
    } catch (Exception e) {
      log.error(e, e);
    } finally {
      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
      try { fis.close(); } catch (Exception ignore) {} finally { fis = null; }
    }
  }

  public void processRow(List rowList, String refNo, String desc) throws Exception {
    Integer parentID = this.startDocID;

    for (int i = 0 ; i < rowList.size(); i++) {
      DmsDocument doc = this.docRetrievalManager.getDocumentByNameParentID((String)rowList.get(i), parentID);
      if (doc == null) {
        DmsDocument newFolder = new DmsDocument();
        newFolder.setRootID(this.rootID);
        newFolder.setParentID(parentID);
        newFolder.setDocumentName((String)rowList.get(i));
        newFolder.setDocumentType(DmsDocument.FOLDER_TYPE);
        newFolder.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);
        newFolder.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
        newFolder.setEffectiveStartDate(Utility.getCurrentTimestamp());
        newFolder.setItemStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
        newFolder.setPriority(GlobalConstant.PRIORITY_MEDIUM);
        if (i == rowList.size() - 1) {
          newFolder.setReferenceNo(refNo);
          newFolder.setDescription(desc);
        }
        doc = this.docOperationManager.createFolder(newFolder);
      }

      parentID = doc.getID();
    }
  }

}